package com.hmall.order.interceptor;

import com.hmall.order.utils.OrderUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class OrderInterceptor implements HandlerInterceptor {

    //原始方法调用前执行的内容
    //返回值类型可以拦截控制的执行，true放行，false终止
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authorization = request.getHeader("authorization");
        if (authorization == null || authorization.equals("")){
            log.error("非法用户");
            return false;
        }
        log.error("合法用户");
        Long aLong = Long.valueOf(authorization);
        OrderUtils.setUser(aLong);
        return true;
    }

    //原始方法调用完成后执行的内容

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        OrderUtils.removeUser();
    }
}
